var moment = require('moment');  // 日期格式化
var os = require('os');
var CONFIG = require('../config');
var ip = require('ip');


export = CommonUtil;


class CommonUtil{
    // 当前时间
    public  static currentTime(){
        return moment().format('YYYY-MM-DD HH:mm:ss');
    }
    // 时间转换为总秒数
    public  static  timeToTotalSeconds(t, format = 'YYYY-MM-DD HH:mm:ss'){
        return parseInt(moment(t,format).valueOf()/1000);
    }

    // 'HH_mm_ss_SSS_'+随机数的字符串
    public static  genRandomStr() {
        var m = moment(new Date());
        var newDirName = m.format('HH_mm_ss_SSS_')+Math.floor(Math.random()*100000);
        return newDirName;
    }
    // 今天偏移i天得到'YYYY/MM/DD'的字符串
    public static genDayStr(i:number=0, formatStr='YYYY/MM/DD'){
        var m = moment(new Date());
        if(i>=0){
            return moment(m).add( i, 'days').format(formatStr);
        }else{
            return moment(m).subtract( -i, 'days').format(formatStr);
        }
    }
    // 今天偏移i天得到'YYMMDDHHmmss'的字符串
    public static genCurYearDayTimeStr(formatStr='YYMMDDHHmmss'){
        var m = moment(new Date());
        return moment(m).format(formatStr);
    }
    // 将url中的文件名的中文进行编码
    public static encodingUrl(url:string):string{
        var pos = url.lastIndexOf('/');
        var last = url.substring(pos);
        last = encodeURIComponent(last);
        return url.substring(0,pos+1)+last;
    }

    /**
     * R/G/B(0~255)合并成十六进制字符串
     */
    public static RGBtoHex(R:any, G:any, B:any, withPrefix:boolean=false): string {
        var ret = CommonUtil.toHex(R) + CommonUtil.toHex(G) + CommonUtil.toHex(B);
        if (withPrefix) {
            ret = "#" + ret;
        }
        return ret;
    }
    /**
     * R/G/B(0~255)转十六进制字符串
     */
    public static toHex(N: any): string {
        if (N == null)
            return "00";
        var num = parseInt(N);
        if (num == 0 || isNaN(num))
            return "00";
        num = Math.max(0,num);
        num = Math.min(num,255);
        num = Math.round(num);
        return "0123456789ABCDEF".charAt((num - num % 16) / 16) + "0123456789ABCDEF".charAt(num % 16);
    }
    //------------------------------------------------------------------
    // 根据oss的url获取bucket名称
    public static  get_bucket_name_by_url(url){
        if(!url)    return null;
        if(!CommonUtil.is_oss_domain(url))  return null;

        var pos = url.indexOf('.');
        if(pos<=0)  return null;

        var begin = url.indexOf('https://') == 0 ? 8 : 7;
        return url.substring(begin,pos);
    }
    //------------------------------------------------------------------

    // 从url中取uri,如：'image/U0CARD/20160320161237/Fqj4TOwZECaHJmkzPwAN94Y-oOx2'
    // 注意：开头不带'/'
    public static uri_from_url(url){
        if(!url)    return null;
        var pos = url.indexOf('/',8);
        if(pos<=0)  return null;

        return url.substring(pos+1);
    }
    // 是否qiniu 域名
    public static is_qn_domain(url){
        return url.indexOf(CONFIG.QINIU_DOMAIN_PREFIX)==0;
    }
    //------------------------------------------------------------------

    // 是否oss域名
    public static is_oss_domain(url){
        return url.indexOf(CONFIG.OSS_DOMAIN_PREFIX)==0 || url.indexOf(CONFIG.OSS_DOMAIN_PREFIX_HTTPS) == 0;
    }
    // 是否oss内网域名
    public static is_oss_internal_domain(url){
        if(!CommonUtil.is_oss_domain(url))  return false;
        var pos = url.indexOf(CONFIG.OSS_DOMAIN_INTERNAL);
        if(pos<=0)   return false;
        return true;
    }
    // 是否oss外网域名
    public static is_oss_outside_domain(url){
        if(!CommonUtil.is_oss_domain(url))  return false;
        if(CommonUtil.is_oss_internal_domain(url)) return false;
        return true;
    }
    // 将oss内网域名转换为外网域名
    public static  oss_internal_domain_2_outside(url){
        var pos = url.indexOf(CONFIG.OSS_DOMAIN_INTERNAL_FLAG);
        if(pos>0){
            url = url.substring(0, pos)+url.substring(pos+CONFIG.OSS_DOMAIN_INTERNAL_FLAG_LENTH);
        }

        return url;
    }
    // 将oss内网域名转换为外网域名
    public static  oss_outside_domain_2_internal(url){
        var pos = url.indexOf(CONFIG.OSS_DOMAIN_FLAG);
        if(pos>0){
            pos += CONFIG.OSS_DOMAIN_FLAG_LENTH;
            url = url.substring(0, pos)+CONFIG.OSS_DOMAIN_INTERNAL_FLAG+url.substring(pos);
        }

        return url;
    }

    //------------------------------------------------------------------
    // 获取本机ip, 如 '192.168.31.227'
    public static g_ip=null;
    public static getLocalIP():any {
        if(!CommonUtil.g_ip)    CommonUtil.g_ip=ip.address();
        return CommonUtil.g_ip;
    }


    /**
     * 生成上传到服务器的文件名: [typeStr]/[idStr]/[YYYY]/[MM]/[DD]/[HHmmssSSS]_[random(20)]
     * [typeStr]: "image"或"audio"或"video"
     * [idStr]: "U"+userId或"T"+random(6)
     * [YYYY]/[MM]/[DD]: 年/月/日
     * [HHmmssSSS]: 时分秒毫秒
     * [random(20)]: 20位随机字符串
     *
     * type: 0图片，1音频，2视频 (默认为0)
     * userId(可选): 用户ID
     */
    public static getUploadFileName(type: number, userId: string): string {

        var strId = "";
        if (typeof userId=='undefined' || userId == null || (''+userId).trim().length == 0){
            // userId不存在时
            strId = "T"+Math.floor(Math.random()*1000000)+"/";
        } else {
            strId = "U"+userId+"/";
        }

        var m = moment(new Date());
        var strDate = m.format('YYYY/MM/DD/HHmmssSSS_')+CommonUtil.randomString(20);

        var name = "";
        if (type == 1) {
            name = "audio/"+strId+strDate;
        } else if (type == 2){
            name = "video/"+strId+strDate;
        } else {
            name = "image/"+strId+strDate;
        }

        return name;
    }

    /**
     * 生成随机字符串(数字＋大小写字母)
     * @param len
     * @returns {string}
     */
    public static randomString(len: number) {
        var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
        var maxLen = chars.length;
        var ret = '';
        for (var i = 0; i < len; i++) {
            ret += chars.charAt(Math.floor(Math.random() * maxLen));
        }
        return ret;
    }

    public static randomString2(len: number, chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz') {
        var maxLen = chars.length;
        var ret = '';
        for (var i = 0; i < len; i++) {
            ret += chars.charAt(Math.floor(Math.random() * maxLen));
        }
        return ret;
    }

    /**
     * 生成随机(数字)字符串
     * @param len
     * @returns {string}
     */
    public static randomNumStr(len: number,chars='0123456789'){
        var maxLen = chars.length;
        var ret = '';
        for (var i = 0; i < len; i++) {
            ret += chars.charAt(Math.floor(Math.random() * maxLen));
        }
        return ret;
    }
    /**
     * 生成随机(数字)字符串
     * @param len
     * @returns {string}
     */
    public static randomNumStrArr(len: number,chars=[0,1,2,3,4,5,6,7,8,9]){
        var maxLen = chars.length;
        var ret = [];
        for (var i = 0; i < len; i++) {
            ret.push(chars[Math.floor(Math.random() * maxLen)]);
        }
        return ret;
    }


    //--------------------------------------------------------------------------------------------
    /**
     * 生成随机字符串
     * @param len: 字符串长度(默认32位)
     * @param flg: 1:纯数字; 2:纯字母; 其他(默认):数字+字母
     * @returns {string}
     */
    public static genNonceStr(len,flg){
        var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        if(flg == 1) {
            chars = '0123456789';
        } else if(flg == 2) {
            chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        }
        var maxPos = chars.length;
        var ret = "";
        var size = Number(len||'32');
        for(var i = 0; i < size; i++) {
            ret += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return ret;
    }

    /**
     * 年月日时（各2位）数字字符串转换成26进制
     * [日]超过25时先重新计算: [月]=[月]+12, [日]=[日]-25
     * @param len
     * @returns {string}
     */
    public static yearDayTimeStrtoAlphabet(str: string){
        var Y = Number(str.substr(0,2)||'0');
        var M = Number(str.substr(2,2)||'0');
        var D = Number(str.substr(4,2)||'0');
        var H = Number(str.substr(6,2)||'0');
        if(D>25) {
            M = M+12;
            D = D-25;
        }

        return  CommonUtil.twoNumStrtoAlphabet(Y+'')
            +CommonUtil.twoNumStrtoAlphabet(M+'')
            +CommonUtil.twoNumStrtoAlphabet(D+'')
            +CommonUtil.twoNumStrtoAlphabet(H+'');
    }
    /**
     * 2位数字字符串转换成26进制
     * @param len
     * @returns {string}
     */
    public static twoNumStrtoAlphabet(str: string){
        var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        return  chars.charAt(str*1);
    }
    /**
     * 将字符串2随机混入字符串1的缝隙中
     * @param str1
     * @param str2
     * @returns {string}
     */
    public static mix(str1: string,str2: string){
        var len1 = str1.length;
        var len2 = str2.length;
        if(len1<(len2+1) || len1<1 || len2<1){
            return str1+str2;
        }

        var posStrs = [];// str1中可以插入的位置： 1、2、3...maxCount
        for(var i=0;i<(len1-1);i++){ posStrs.push(i+1); }
        var ranPosStrs = CommonUtil.randomNumStrArr(len2, posStrs);// 随机的插入位置：3、1、maxCount...2
        ranPosStrs.sort(function(a,b){return a-b;}); // 按从小到大排序
        var ret = str1;
        for(var i=len2-1;i>=0;i--){ // 倒序插入
            var pos = ranPosStrs[i];
            ret = ret.substring(0,pos)+str2[i]+ret.substring(pos);
        }
        return ret;
    }

    /**
     * 将“m.n小时”转换为“x小时y分”
     * @param hour,小时，例如：1.23
     * @param fixed,小数位，例如：2
     * @returns {string}
     */
    public static float_to_hour_str(hour, fixed){
        var ret = null;

        var h = Math.floor(hour);
        var m = 0;
        if(hour>=1){
            m = Math.floor((hour - h)*60);
        }else{
            m = Math.floor((hour)*60);
        }
        if(h>0 || m>0){
            ret = ((h>0)?(h+"小时"):("")) + ((m>0)?(m+"分钟"):(""));
        }

        return ret;
    }
    /**
     * 将“m.n天”转换为“x天y小时”
     * @param day,天数，例如：1.23
     * @param fixed,小数位，例如：2
     * @returns {string}
     */
    public static float_to_day_str(day,fixed){
        var ret = null;

        var d = Math.floor(day);
        var h = 0;
        if(day>=1){
            h = Math.floor((day - d)*24);
        }else{
            h = Math.floor((day)*24);
        }
        if(d>0 || h>0){
            ret = ((d>0)?(d+"天"):("")) + ((h>0)?(h+"小时"):(""));
        }

        return ret;
    }

    /**
     * 将字符串中的特殊字符处理掉，以便JSON.parse能正常解析
     * @param day,天数，例如：1.23
     * @param fixed,小数位，例如：2
     * @returns {string}
     */
    public static process_before_JSON_Parse(str){
        return str.replace(/\n/g,'\\n').replace(/\t/g,'').replace(/\r/g,'') //.replace(/\\"/g,'\\\\\\"')
            .replace(/[\x00-\x09\x0B-\x1F\x7F-\x9F]/g, "");
    }


    /**
     * 使用exec调用进程时，传递字符串类型的参数中如果有空字符串，需要处理
     * @param str 字符串类型的参数
     * @returns {string}
     */
    public static process_string_param_before_exec(str){
        return  (!str || str=="")?("\"\""):str;
    }

    /**
     * 使用exec调用进程时，传递字符串类型的参数中如果有半角引号，需要处理
     * @param str 字符串类型的参数
     * @returns {string}
     */
    public static process_string_param_before_exec2(str){
        return  str.replace(/"/g,'\\"');
    }
}


